using System;
using System.Collections.Generic;
using System.Text;

namespace Serialcoder.Erp.Tools.PatchCreator
{
	public class Context
	{
		Dictionary<string, string> m_Templates = new Dictionary<string, string>();

		private Context()
		{
			m_Templates.Add("Drop View", @"if Exists(Select * from sysobjects where name = '<ViewName>' and xtype = 'V')
Begin
	drop view dbo.<ViewName>
End
Go");
			m_Templates.Add("Drop Table", @"if Exists(Select * from sysobjects where name = '<TableName>' and xtype = 'T')
Begin
	drop table dbo.<TableName>
End
Go");
			m_Templates.Add("Drop Procedure", @"if Exists(Select * from sysobjects where name = '<ProcedureName>' and xtype = 'P')
Begin
	drop procedure dbo.<ProcedureName>
End
Go");

			m_Templates.Add("Add Column", @"if col_length('<TableName>','<ColumnName>') is null
Begin
	alter table <TableName> add <ColumnName> <TypeName> <Nullable>
End
Go");
			m_Templates.Add("Drop Column", @"if col_length('<TableName>','<ColumnName>') is not null
Begin
	alter table <TableName> drop column <ColumnName> 
End
Go");

            m_Templates.Add("Add index", @"if NOT Exists(select * from sysindexes where name = '<IndexName>')
Begin
    CREATE INDEX <IndexName> ON <TableName> (<ColumnName>); 
END
GO");

            m_Templates.Add("Drop index", @"if Exists(select * from sysindexes where name = '<IndexName>')
Begin
    DROP INDEX <IndexName> ON <TableName> (<ColumnName>); 
END
GO");

            m_Templates.Add("Drop Foreign key", @"if Exists(select * from sysobjects where name = '<ForeignKey>' and xtype = 'F')
Begin
    alter table <TableName> drop constraint <ForeignKey>
END
GO");
			/*
            m_Templates.Add("Add Foreign key", @"if NOT Exists(select * from sysobjects where name = '<ForeignKey>' and xtype = 'F')
Begin
    alter table <TableName> add constraint <ForeignKey>
END
GO");
			 */

		}

		public Dictionary<string, string> Templates
		{
			get
			{
				return m_Templates;
			}
		}

		#region Singleton

		private static volatile Context _singleton;
		private static object syncRoot = new Object();

		public static Context Current
		{
			get
			{
				if (_singleton == null)
				{
					lock (syncRoot)
					{
						if (_singleton == null)
						{
							_singleton = new Context();
						}
					}
				}

				return _singleton;
			}
		}
		#endregion

		public void CreatePatch(string text)
		{
			PatchForm form = new PatchForm();
			Runtime.Patch patch = Runtime.DAL.CreateNew();
			patch.Sql = text;


			form.Patch = patch;
			form.MdiParent = MainForm.Current;
			form.WindowState = System.Windows.Forms.FormWindowState.Maximized;
			form.Text = string.Format("Nouveau patch {0}", MainForm.Current.MdiChildren.Length);
			form.Show();
		}

		public void CreatePatch()
		{
			CreatePatch(string.Empty);
		}
	}
}
